package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        Map<String,String> map = new LinkedHashMap<>();//有序存储.先放过在拦截
        //anon 无需登陆  authc 必须登陆才能访问  perms 登陆后授权才可以访问  role 登陆后有这个角色才能访问
        //放过登陆
        map.put("/DengluController/login","anon");

        /*map.put("/**","authc");*/

        //设置默认重置页面
        factoryBean.setLoginUrl("/ToShow/index");
        //设置过滤器链
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginUserRealm loginUserRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(loginUserRealm);
        return securityManager;
    }
    @Bean
    public LoginUserRealm loginUserRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginUserRealm loginUserRealm =  new LoginUserRealm();
        loginUserRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return new LoginUserRealm();
    }
    //密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setStoredCredentialsHexEncoded(true);//设置密码加密编码
        matcher.setHashIterations(3);//加密迭代的次数也就是重复加密次数
        matcher.setHashAlgorithmName("MD5");//加密方式
        return matcher;
    }
}
